package com.gton.controller;

import cn.dev33.satoken.config.SaSsoConfig;
import cn.dev33.satoken.sso.SaSsoProcessor;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gton.entity.AuthLoginUser;
import com.gton.service.AuthLoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @description: 统一认证中心 SSO-Server用于对外开放接口：
 * @author: GuoTong
 * @createTime: 2022-11-26 23:03
 * @since JDK 1.8 OR 11
 **/
@RestController
public class SsoServerController {


    private AuthLoginUserService authLoginUserService;

    /**
     * Description: 构造器注入
     */
    public SsoServerController(AuthLoginUserService authLoginUserService) {
        this.authLoginUserService = authLoginUserService;
    }


    /*
     * /*
     * SSO-Server端：处理所有SSO相关请求
     * 		http://{host}:{port}/sso/auth			-- 单点登录授权地址，接受参数：redirect=授权重定向地址
     * 		http://{host}:{port}/sso/doLogin		-- 账号密码登录接口，接受参数：name、pwd
     * 		http://{host}:{port}/sso/checkTicket	-- Ticket校验接口（isHttp=true时打开），接受参数：ticket=ticket码、ssoLogoutCall=单点注销回调地址 [可选]
     * 		http://{host}:{port}/sso/signout		-- 单点注销地址（isSlo=true时打开），接受参数：loginId=账号id、secretkey=接口调用秘钥
     */
    @RequestMapping("/sso/*")
    public Object ssoRequest() {
        return SaSsoProcessor.instance.serverDister();
    }

    /**
     * 配置SSO相关参数
     */
    @Autowired
    private void configSso(SaSsoConfig sso) {
        // 配置：未登录时返回的View
        sso.setNotLoginView(() -> new ModelAndView("sa-login.html"));

        // 配置：登录处理函数
        sso.setDoLoginHandle((name, pwd) -> {
            QueryWrapper<AuthLoginUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", name);
            queryWrapper.eq("password", pwd);
            AuthLoginUser user = authLoginUserService.getOne(queryWrapper);
            if (user != null) {
                StpUtil.login(user.getId());
                return SaResult.ok("登录成功！").setData(StpUtil.getTokenValue());
            }
            return SaResult.error("登录失败！");
        });

    }
}
